<?php
class wxSendLib
{
	public $pc;
	public $helper;
	
	public function __construct()
	{
		include_once "wxBizMsgCrypt.php";
		include_once "wxHelper.php";
		$wxData = include_once "wxConfig.php";
		$encodingAesKey = $wxData['SecretKey'];
		$token = $wxData['Token'];
		$appId = $wxData['AppId'];
		$appSecret = $wxData['AppSecret'];
		$this->pc = new WXBizMsgCrypt ( $token, $encodingAesKey, $appId);
		$this->helper = new wxHelper();
	}

	public function send_msg_test()
	{
		include_once "wxInfoLib.php";
		$resultStr = get_reply("", "gh_b81b74782e35");
		echo $resultStr;
	}

	public function send_msg($msg_sign, $timeStamp, $nonce, $encryptMsg)
	{
		include_once "wxInfoLib.php";
		$wxInfoLib = new wxInfoLib();

		$msg = '';
		$errCode = $this->pc->decryptMsg($msg_sign, $timeStamp, $nonce, $encryptMsg, $msg);
		
		if($errCode == 0)
		{
			$data = $this->helper->xmlToArr ( $msg );
		    $fromUsername = $data['FromUserName'];
		    $toUsername = $data['ToUserName'];
		    $msgType = trim($data['MsgType']);
		    //默认返回
		    $sendtime = time();
    		$sendtextTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
			</xml>"; 
			$sendMsgType = "text";
		    $sendContentStr = "什么都没发生!";
		    $sendResultStr = sprintf($sendtextTpl, $fromUsername, $toUsername, $sendtime, $sendMsgType, $sendContentStr);
		    //默认返回
		    
		    $encryptMsg = "";


		    //事件
		    if($msgType == 'event')
		    {
		    	$event = trim($data['Event']);
		    	//全网发布
		    	if($toUsername == "gh_3c884a361561")
		    	{
		    		$sendMsgType = "text";
		    		$sendContentStr = $event."from_callback";
		   		 	$sendResultStr = sprintf($sendtextTpl, $fromUsername, $toUsername, $sendtime, $sendMsgType, $sendContentStr);
		    		$encryptMsg = $this->encode_msg($sendResultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;
		    	}
		    	//全网发布

		    	if($event == "subscribe")
		    	{
					//判断用户是否通过ticket扫二维码
					if(trim($data['Ticket']) != ""){
						$is_scan = False;
						$is_scan = $wxInfoLib->get_scan_num(trim($data['Ticket']));
					}
					//更新微信用户
					$wxInfoLib->update_user($fromUsername, $toUsername, 1);
		    		//发送关注信息
		    		$resultStr = $wxInfoLib->get_subscribe($fromUsername, $toUsername);
					$encryptMsg = $this->encode_msg($resultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;

		    	}
				elseif($event == "unsubscribe")
		    	{
		    		$wxInfoLib->update_user($fromUsername, $toUsername, 0);
		    		return "";
		    	}
				elseif($event == "SCAN"){
					//扫描二维码信息
						
					//发送关注消息
					//判断用户是否通过ticket扫二维码
					
					if(trim($data['Ticket']) != ""){
						$is_scan = False;
						$is_scan = $wxInfoLib->get_scan_num(trim($data['Ticket']));
					}
					$resultStr = $wxInfoLib->get_subscribe($fromUsername, $toUsername);
					$encryptMsg = $this->encode_msg($resultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;					
				}elseif($event == "MASSSENDJOBFINISH")
				{
					$mass['MsgID'] = $data['MsgID'];
					$mass['Status'] = $data['Status'];
					$mass['TotalCount'] = $data['TotalCount'];
					$mass['FilterCount'] = $data['FilterCount'];
					$mass['SentCount'] = $data['SentCount'];
					$mass['ErrorCount'] = $data['ErrorCount'];
					$wxInfoLib->update_mass_msg($mass, $toUsername);
				}
		    //文本消息
		    }elseif($msgType == "text"){
		    	$keyword = trim($data['Content']);

		    	//全网发布
		    	if($toUsername == "gh_3c884a361561" && $keyword == "TESTCOMPONENT_MSG_TYPE_TEXT")
		    	{
		    		$sendMsgType = "text";
		    		$sendContentStr = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
		   		 	$sendResultStr = sprintf($sendtextTpl, $fromUsername, $toUsername, $sendtime, $sendMsgType, $sendContentStr);
		    		$encryptMsg = $this->encode_msg($sendResultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;
		    	}
		    	
		    	if($toUsername == "gh_3c884a361561" && strpos($keyword, "QUERY_AUTH_CODE") > -1)
		    	{
		    		$ticket = str_replace("QUERY_AUTH_CODE:", "", $keyword);
		    		$sendcus['content'] = $ticket."_from_api";
		    		include_once "wxAuthLib.php";
		    		include_once "wxClassLib.php";
		    		
		    		$wxAuthLib = new wxAuthLib();
		    		$res = $wxAuthLib->getAuthorizationAppid($ticket); //使用授权码换取公众号的接口调用凭据和授权信息
		    		$this->helper->set_php_file(dirname(__FILE__)."/test.php", json_encode($res));
		    		if($res != "")
		    		{
		    			$authorizer_access_token = $res['authorization_info']['authorizer_access_token'];
		    			$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$authorizer_access_token;
					    	$curlPost['touser'] = $fromUsername;
					     	$curlPost['msgtype'] = "text";

				    		$curlPost['text']['content'] = $ticket."_from_api";
					    	$curlPost = json_encode($curlPost);
					        $res = json_decode($this->helper->httpPost($curlPost, $url), true);
		    			//$this->helper->set_php_file(dirname(__FILE__)."/test.php", $authorizer_access_token);
		    			
		    		}
		    		return "";
		    	}
		    	//全网发布

		    	if(!empty( $keyword ))
				{
					$resultStr = $wxInfoLib->get_keyword($keyword, $fromUsername, $toUsername);
					if(empty($resultStr))
					{
						$resultStr = $wxInfoLib->get_reply($fromUsername, $toUsername);
					}
					$encryptMsg = $this->encode_msg($resultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;
				}else{
					$encryptMsg = $this->encode_msg($sendResultStr, $timeStamp, $nonce, $encryptMsg);
					return $encryptMsg;
				}
			//图片消息
		    }elseif($msgType == "image"){

		    }
		    //语音消息
		    elseif($msgType == "voice"){

		    }
		    //地理位置消息
		    elseif($msgType == "location"){

		    }
		    //链接消息
		    elseif($msgType == "link"){

		    }
		}else{
			return $errCode;
		}
	}

	
	public function encode_msg($resultStr, $timeStamp, $nonce, $encryptMsg)
	{	
		$encryptMsg = "";
		$serrCode = $this->pc->encryptMsg($resultStr, $timeStamp, $nonce, $encryptMsg);
		if($serrCode == 0)
		{
			return $encryptMsg;
		}else
		{
			return $serrCode;
		}
	}


}
?>